/*
 * 
 */
package fr.univtln.superplanning.controller;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;

import javax.swing.JFrame;
import javax.swing.event.CaretEvent;
import javax.swing.event.CaretListener;

import fr.univtln.superplanning.api.ISuperplanningManager;
import fr.univtln.superplanning.api.event.Course;
import fr.univtln.superplanning.api.resources.Classroom;
import fr.univtln.superplanning.api.study.Promotion;
import fr.univtln.superplanning.gui.PopupManager;
import fr.univtln.superplanning.gui.event.EventEditor;
import fr.univtln.superplanning.util.DateManager;

/**
 * This class is the controller for add or edditing an event.
 * 
 * @author vincent
 * 
 */
public class EventController implements ActionListener, IGenericController, CaretListener {
	private Course course;
	private EventEditor eventEditor;
	private ISuperplanningManager superplanningManager;

	public EventController(ISuperplanningManager superplanningManager, Course course) {
		eventEditor = new EventEditor(this);
		this.superplanningManager = superplanningManager;
		initializeUi();
		showView();
	}

	public void showView() {
		eventEditor.setVisible(true);
	}

	public void hideView() {
		eventEditor.setVisible(false);
	}

	/**
	 * This method will set the comboBox by the values stored in the persistent
	 * context.
	 */
	private void initializeUi() {
		eventEditor.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
		initializeViewListeners();

		// disable the selection of classroom and the validate button
		eventEditor.getClassroomComboBox().setEnabled(false);
		eventEditor.getValidateEventButton().setEnabled(false);

		updateUi();
	}

	/**
	 * This method will update the UI according with the current course.
	 */
	public void updateUi() {
		// 1. get the promotions
		List<String> promotionCodes = superplanningManager.getStudyManager().getAllPromotionCodes();

		// foreach promotions code, display it in the view promotions combobox
		for (String promotionCode : promotionCodes)
			eventEditor.getPromotionsComboBox().addItem(promotionCode);

		// 2. Update the teachings
		updateTeachingAccordingWithPromotion();

		// 3. Update the teacher
		List<String> teacherLogins = superplanningManager.getPersonManager().getAllTeacherLogins();

		for (String teacherLogin : teacherLogins)
			eventEditor.getTeacherComboBox().addItem(teacherLogin);

		// 4. Update event type
		List<String> eventTypeCodes = superplanningManager.getEventManager().getAllEventTypeCodes();
		for (String eventTypeCode : eventTypeCodes)
			eventEditor.getEventTypeComboBox().addItem(eventTypeCode);

	}

	private void updateTeachingAccordingWithPromotion() {
		// Get the teachings for the selected promotion
		String promotionCode = (String) eventEditor.getPromotionsComboBox().getSelectedItem();
		Promotion promotion = superplanningManager.getStudyManager().getPromotionByCode(
				promotionCode);

		// Now get the teaching codes for the promotion
		if (promotion != null) {
			List<String> teachings = superplanningManager.getStudyManager().getAllTeachingCodes();

			// update the view teachings combobox
			for (String teaching : teachings) {
				eventEditor.getTeachingComboBox().addItem(teaching);
			}

		}
	}

	/**
	 * This method will update the free classrooms according with the event
	 * begin date time and the event duration.
	 */
	private void updateFreeClassrooms() {
		List<Classroom> freeClassrooms = new ArrayList<Classroom>();

		// 1. Reset the current free classrooms
		eventEditor.getClassroomComboBox().removeAllItems();

		// retreive the begin date time
		try {
			String courseDateTimeString = eventEditor.getDateTextField().getText() + "T"
					+ eventEditor.getTimeTextField().getText();

			Calendar courseDateTime = DateManager.StringToCalendar(courseDateTimeString,
					DateManager.DATE_TIME_PATTERN);

			int duration = Integer.valueOf(eventEditor.getDurationTextField().getText());

			// get freeClassrooms
			freeClassrooms = superplanningManager.getRessourceManager().getAllFreeClassrooms(
					courseDateTime, duration);

			for (Classroom classroom : freeClassrooms) {
				eventEditor.getClassroomComboBox().addItem(classroom.getNumero());
			}

		} catch (ParseException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

	}

	/**
	 * This method will save the current course.
	 */
	public void save() {
		// 1. Create a course according with the field
		// Verify the date and hour field
		String courseDateTimeString = eventEditor.getDateTextField().getText() + "T"
				+ eventEditor.getTimeTextField().getText();

		try {
			Calendar courseDateTime = DateManager.StringToCalendar(courseDateTimeString,
					DateManager.DATE_TIME_PATTERN);

			course = new Course();

			course.setTeaching(superplanningManager.getStudyManager().getTeachingByCode(
					eventEditor.getTeachingComboBox().getSelectedItem().toString()));
			course.setTeacher(superplanningManager.getPersonManager().getTeacherByLogin(
					eventEditor.getTeacherComboBox().getSelectedItem().toString()));
			course.setType(superplanningManager.getEventManager().getEventTypeByCode(
					eventEditor.getEventTypeComboBox().getSelectedItem().toString()));
			course.setBeginDateTime(courseDateTime);
			course.setDuration(Integer.parseInt(eventEditor.getDurationTextField().getText()));
			course.add(superplanningManager.getStudyManager().getPromotionByCode(
					eventEditor.getPromotionsComboBox().getSelectedItem().toString()));
			course.setClassroom(superplanningManager.getRessourceManager().getClassroomByNumero(
					eventEditor.getClassroomComboBox().getSelectedItem().toString()));

			superplanningManager.getEventManager().insertEvent(course);

			PopupManager.showInformation("Le cours a bien été enregistré", "Cours enregistré");
		} catch (ParseException e) {
			PopupManager.showErrorMessage(
					"Vous devez respectez le format de date (dd-MM-yyyy) et d'heure (HH:mm)",
					"Erreur sur le format de l'heure");
		}
	}

	/**
	 * This method will delete the current course.
	 */
	public void delete() {

	}

	private void initializeViewListeners() {
		eventEditor.getValidateEventButton().addActionListener(this);
		eventEditor.getValidateFirstElementsButton().addActionListener(this);
		eventEditor.getCancelEventButton().addActionListener(this);
		eventEditor.getDeleteCourseButton().addActionListener(this);
		eventEditor.getDateTextField().addCaretListener(this);
		eventEditor.getTimeTextField().addCaretListener(this);
		eventEditor.getDurationTextField().addCaretListener(this);
	}

	@Override
	public void actionPerformed(ActionEvent e) {
		if (e.getSource() == eventEditor.getValidateFirstElementsButton()) {
			updateFreeClassrooms();
			eventEditor.getClassroomComboBox().setEnabled(true);
			eventEditor.getValidateEventButton().setEnabled(true);

		} else if (e.getSource() == eventEditor.getValidateEventButton()) {
			save();
		} else if (e.getSource() == eventEditor.getCancelEventButton()) {
		} else if (e.getSource() == eventEditor.getDeleteCourseButton()) {
		}
	}

	@Override
	public void caretUpdate(CaretEvent e) {
		// When a textfield is modified, disable the selection of classroom and
		// the validate button
		if (e.getSource() == eventEditor.getDateTextField()) {
			eventEditor.getClassroomComboBox().setEnabled(false);
			eventEditor.getValidateEventButton().setEnabled(false);

		} else if (e.getSource() == eventEditor.getTimeTextField()) {
			eventEditor.getClassroomComboBox().setEnabled(false);
			eventEditor.getValidateEventButton().setEnabled(false);

		} else if (e.getSource() == eventEditor.getDurationTextField()) {
			eventEditor.getClassroomComboBox().setEnabled(false);
			eventEditor.getValidateEventButton().setEnabled(false);

		}
	}

}
